package com.sys.utils;

import java.io.IOException;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.entity.Function;
import com.entity.MenuInfo;
import com.entity.UserInfo;


/**
 * Servlet Filter implementation class LoginFilter
 */
//@WebFilter("/*")
public class LoginFilter implements Filter {

    /**
     * Default constructor. 
     */
    public LoginFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest rep, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)rep;
		HttpSession session = request.getSession();
		HttpServletResponse res= (HttpServletResponse) response;
		res.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");

		UserInfo user = (UserInfo) session
				.getAttribute(Mark.LOGIN_SESSION_USER);
		List<Function> functionList = (List<Function>) session.getAttribute("functionList");


		String uri = request.getRequestURI();
		String referer = request.getHeader("referer");
		System.out.println(uri);
		if (uri.contains("/UserLoginServlet")) {
			chain.doFilter(request, response);
		}else if (uri.contains("/resources/")) {
			chain.doFilter(request, response);
		} else if (user != null) {
//			不拦截公共jsp
			if (uri.contains(".jsp")){
				chain.doFilter(request, response);
				return;
			}
//			不拦截管理员角色 TODO 这里应该给角色加个管理员字段，通过该字段判断
			if (user.getRoleId()==1){
				chain.doFilter(request, response);
				return;
			}
//			鉴权
			for (int i = 0; i < functionList.size(); i++) {
				if (uri.contains(functionList.get(i).getUrl())){
					chain.doFilter(request, response);
					return;
				}
			}
//			设置上一级url，并转发到无权页面
			request.setAttribute("backurl",referer);
			boolean contains = ((String) request.getAttribute("backurl")).contains("UserLoginServlet");
			request.setAttribute("contains",contains);
			request.getRequestDispatcher("/noauth.jsp").forward(request,
					response);

		} else {
			request.getRequestDispatcher("/login.jsp").forward(request,
					response);
		}
	}
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
